/*
 * @Author: ujjldn ujjldn0515@163.com
 * @Date: 2025-06-23 18:49:49
 * @LastEditors: ujjldn ujjldn0515@163.com
 * @LastEditTime: 2025-06-24 09:29:41
 * @FilePath: \g-table\src\utils\export.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import { ElMessageBox } from 'element-plus'

export const fileInputBox = async (ext = 'json') => {
    const regex = new RegExp(`^\\w+\\.(?:${ext})$`,'i') //忽略大小写匹配
    try {
        const { value } = await ElMessageBox.prompt('请输入文件名', 'InputBox', {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            inputValue:`undefined.${ext}`,
            inputPattern: regex,
            inputErrorMessage: '文件名错误',
        })
        return value ? value : ''
    } catch {
        return false
    }
}

export const exportToJson = async (jsonData,ext='json') => { // 修改为 async 函数
    const fileName = await fileInputBox(ext) // 使用 await 等待 fileInputBox 返回值
    if (fileName) {
        FileSaver.saveAs(new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' }), fileName)
    }
}

export const exportToExcel = async (data) => {
    const fileName = await fileInputBox('xlsx') // 使用 await 等待 fileInputBox 返回值
    if (fileName) {
        const ws = XLSX.utils.aoa_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, `${fileName}`);
    }
  
}